package com.ygqh.baby.controller.admin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.Message.Type;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.model.wdt.WdtImportOrder;
import com.ygqh.baby.model.wdt.WdtImportOrderDetail;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgOrderDetail;
import com.ygqh.baby.po.YgReturnOrder;
import com.ygqh.baby.po.YgReturnOrderDetail;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgReturnOrderService;
import com.ygqh.baby.service.YgStockService;
import com.ygqh.baby.service.task.WdtService;
import com.ygqh.baby.service.task.YgMonitoringService;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.MailUtil;

@Controller
@RequestMapping("/admin/monitor")
public class MonitorController<T> extends BaseController<Object, java.lang.Long> {

	private ScheduledExecutorService exec = null;

	@Autowired
	private WdtService wdtService;
	@Autowired
	private YgStockService ygStockService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private MailUtil mailUtil;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	@Autowired
	private YgWeChatService ygWeChatService;
	@Autowired
	private YgMonitoringService ygMonitoringService;
	@Value("${mail.to.kefu}")
	private String kefu;
	@Value("${mail.to.yushou}")
	private String yushou;

	@RequestMapping("checkData")
	@ResponseBody
	public Message checkData() throws Exception {
		Boolean hasError = false;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -15);
		Date startDate = cal.getTime();
		Date endDate = new Date();
		StringBuffer str = new StringBuffer();
		str.append("<html><head><style>.table-d table{ background:#000;font-size:14px} .table-d table td{ background:#FFF} h5{width: auto;margin-right: 20px} .title{display: flex;line-height: 10px}");
		str.append("</style></head><body>");
		List<Map<String, Object>> map = wdtService.selectPurchaseNoInstock(startDate, endDate);
		if (map.size() > 0) {
			hasError = true;
			str.append("<div class='title'><h5>进货单入库数据与旺店通入库不一致</h5>");
			str.append("</div><div class='table-d'>");
			str.append("<table width='800' border='0' cellspacing='1' cellpadding='0'><tr><td width='15%'>进货单号</td><td width='15%'>旺店通单号</td><td width='15%'>进货单入库数量</td><td width='15%'>旺店通入库</td></tr>");

			for (Map<String, Object> m : map) {
				str.append("<tr><td>" + m.get("purchaseCode") + "</td>");
				str.append("<td>" + m.get("wdtPurchaseCode") + "</td>");
				str.append("<td>" + m.get("inAmount") + "</td>");
				str.append("<td>" + m.get("qty") + "</td>");
				str.append("</tr>");
			}
			str.append("</table><div>");

		}
		// 查询未发货订单
		map = wdtService.selectNoSendOrder(startDate, endDate);
		if (map.size() > 0) {
			hasError = true;
			str.append("<div class='title'><h5>订单未发货数据与旺店通不一致</h5>");
			str.append("</div><div class='table-d'>");
			str.append("<table width='800' border='0' cellspacing='1' cellpadding='0'><tr><td width='15%'>订单号</td><td width='15%'>旺店通单号</td></tr>");

			for (Map<String, Object> m : map) {
				str.append("<tr><td>" + m.get("orderId") + "</td>");
				str.append("<td>" + m.get("wdtOrderCode") + "</td>");
				str.append("</tr>");
			}
			str.append("</table><div>");

		}
		str.append("</body></html>");
		if (hasError) {
			mailUtil.sendWithHtml(new String[] { "wangwei@yiigoo.com", "jiangyunbo@yiigoo.com", "guohao@yiigoo.com" },
					"数据检查日报", str.toString());
		}
		return SUCCESS_MESSAGE;

	}

	@RequestMapping("checkStock")
	@ResponseBody
	public Message checkStock() throws Exception {
		ygMonitoringService.checkStock();
		return SUCCESS_MESSAGE;

	}

	@RequestMapping("getLog")
	@ResponseBody
	public Message getLog(String host) throws IOException {
		long lastTimeFileSize = 0; // 上次文件大小
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date now = new Date();
		String date = format.format(now);

		// 默认web01 的操作日志
		String filePath = "/mnt/project/api/apache-tomcat-8.0.30-8910/logs/localhost_access_log.2017-04-10.txt";
		if (host.equals("web02"))
			filePath = "/mnt/yiigoo/www/wap_api/apache-tomcat-8.0.30-8912-mobile/logs/localhost." + date + ".log";
		if (host.equals("service")) {

			filePath = "/mnt/yiigoo/www/service_job/apache-tomcat-8.0.30-8913-mobile-dwh/logs/error.log";
		}
		if (host.equals("web01"))
			filePath = "/mnt/yiigoo/www/wap_api/apache-tomcat-8.0.30-8912-wap-api/logs/localhost." + date + ".log";

		File logFile = new File(filePath);
		if (!logFile.exists())
			return new Message(Type.error, "错误日志文件不存在");
		RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");
		String key = date + host;
		String lastSize = redisDao.get(key);

		lastTimeFileSize = new Long(lastSize == null ? "0" : lastSize);

		// 获得变化部分的
		randomFile.seek(lastTimeFileSize);
		String tmp = "";
		StringBuffer tmpBuffer = new StringBuffer();
		while ((tmp = randomFile.readLine()) != null) {
			tmpBuffer.append(new String(tmp.getBytes("ISO8859-1")) + "</br>");
		}

		lastTimeFileSize = randomFile.length();
		redisDao.set(key, lastTimeFileSize + "", 3600 * 60 * 60);

		return new Message(Type.success, tmpBuffer.toString());

	}

	@RequestMapping("loadDetail")
	@ResponseBody
	public Message loadDetail(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request,
			HttpServletResponse respons) throws IOException, EncryptedDocumentException, InvalidFormatException {

		InputStream is = uploadFile.getInputStream();
		// XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		List<WdtImportOrder> orderList = new ArrayList<WdtImportOrder>();
		List<WdtImportOrder> changeOrderList = new ArrayList<WdtImportOrder>();
		Workbook workbook = WorkbookFactory.create(is);
		Sheet hssfSheet = workbook.getSheetAt(0); // 示意访问sheet
		try {
			// Read the Sheet
			for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
				Sheet xssfSheet = workbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}

				// 订单号 店铺名称 订单类型 订单来源 状态 交易日期 付款日期 发货时间 业务员 收件人
				// 商家编码 货品编号 规格码 条码 货品名称 规格名称 销售积分 仓库 数量 退货数量
				// 单位成本 总成本 订单实收金额 原始单号 物流公司 物流单号 省 市 区 地址
				// 电话 客户网名 是否开发票 发票抬头 发票内容 客服备注 客户备注 打印备注 货品备注
				// Read the Row
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					Row xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow != null && xssfRow.getPhysicalNumberOfCells() >= 7) {
						String wdtOrderCode = xssfRow.getCell(0).getStringCellValue();
						String createTime = xssfRow.getCell(5).getStringCellValue();
						String payTime = xssfRow.getCell(6).getStringCellValue();
						String sendTime = xssfRow.getCell(7).getStringCellValue();
						String receiver = xssfRow.getCell(9).getStringCellValue();
						String orderStatus = xssfRow.getCell(4).getStringCellValue();
						Double totalPrice = xssfRow.getCell(22).getNumericCellValue();
						String orderNums = xssfRow.getCell(23).getStringCellValue();

						String skuCode = xssfRow.getCell(10).getStringCellValue();
						String skuSize = xssfRow.getCell(12).getStringCellValue();
						String productName = xssfRow.getCell(14).getStringCellValue();
						String skuName = xssfRow.getCell(15).getStringCellValue();
						Double quantity = xssfRow.getCell(18).getNumericCellValue();
						Double returnQty = xssfRow.getCell(19).getNumericCellValue();
						Double unitCost = xssfRow.getCell(20).getNumericCellValue();
						Double totalCost = xssfRow.getCell(21).getNumericCellValue();

						WdtImportOrder iOrder = new WdtImportOrder();
						List<WdtImportOrderDetail> detailList = new ArrayList<WdtImportOrderDetail>();
						WdtImportOrderDetail detail = new WdtImportOrderDetail();
						String[] orderIds = orderNums.split(",");

						for (int i = 0; i < orderIds.length; i++) {
							if (wdtOrderCode.equals("JY201704020086")) {
								System.out.println(orderIds[i]);
							}
							if (StringUtil.isBlank(orderIds[i])) {
								continue;
							}
							boolean isNum = orderIds[i].matches("[0-9]+");
							if (isNum) {
								orderList.add(iOrder);
								long orderId = Long.parseLong(orderIds[i]);
								YgOrder ygOrder = ygOrderService.findOrderDetailByOrderId(orderId);
								iOrder.setOrderId(orderId);
								for (YgOrderDetail d : ygOrder.getOrderDetail()) {
									if (skuCode.equals(d.getSkuCode())) {
										if (quantity.intValue() >= d.getQuantity().intValue()) {
											detail.setQuantity(d.getQuantity().intValue());
											quantity = quantity - d.getQuantity();
										} else {
											detail.setQuantity(quantity.intValue());
											quantity = 0.0;
										}
									} else {
										detail.setQuantity(quantity.intValue());
									}
								}

							} else {
								// 换货
								changeOrderList.add(iOrder);
								YgReturnOrder changeOrder = ygReturnOrderService.findDetailByReCode(orderIds[i]);
								iOrder.setChangeCode(orderIds[i]);
								iOrder.setOrderId(changeOrder.getOrderId());
								for (YgReturnOrderDetail d : changeOrder.getReturnOrderDetails()) {
									if (skuCode.equals(d.getSkuCode())) {
										if (quantity.intValue() >= d.getAmount().intValue()) {
											detail.setQuantity(d.getAmount().intValue());
											quantity = quantity - d.getAmount();
										} else {
											detail.setQuantity(quantity.intValue());
											quantity = 0.0;

										}
									} else {
										detail.setQuantity(quantity.intValue());
									}
								}
							}

							iOrder.setWdtOrderCode(wdtOrderCode);
							iOrder.setCreateTime(DateConvertUtils.parse(createTime, DateConvertUtils.DATE_TIME_FORMAT));
							iOrder.setPayTime(DateConvertUtils.parse(payTime, DateConvertUtils.DATE_TIME_FORMAT));
							iOrder.setReceiver(receiver);
							iOrder.setTotalPrice(new BigDecimal(totalPrice));
							if (orderStatus.equals("已完成")) {
								iOrder.setOrderStatus(OrderStatus.TradeSuccess);
								iOrder.setSendTime(DateConvertUtils.parse(sendTime, DateConvertUtils.DATE_TIME_FORMAT));
							} else if (orderStatus.equals("被取消")) {
								iOrder.setOrderStatus(OrderStatus.TradeClosed);
							} else if (orderStatus.equals("待审核")) {
								iOrder.setOrderStatus(OrderStatus.WaitingSend);
							}

							detail.setSkuCode(skuCode);
							detail.setQuantity(quantity.intValue());
							detail.setProductName(productName);
							detail.setReturnQty(returnQty.intValue());
							detail.setSkuName(skuName);
							detail.setSkuSize(skuSize);
							detail.setTotalCost(new BigDecimal(totalCost));
							detail.setUnitCost(new BigDecimal(unitCost));

							detailList.add(detail);
							iOrder.setDetailList(detailList);
						}

					}
				}
				Map<Long, List<WdtImportOrder>> orderCollect = orderList.stream().collect(
						Collectors.groupingBy(o -> o.getOrderId()));
				Map<Long, List<WdtImportOrder>> changeOrderCollect = changeOrderList.stream().collect(
						Collectors.groupingBy(o -> o.getOrderId()));
				System.out.println(orderList.size());
				System.out.println(changeOrderList.size());
				System.out.println(workbook.getNumberOfSheets());
				System.out.println(000);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("");
		}

		return Message.success(orderList);
	}
}
